package com.davidjmcclelland;

/****************************************************
* Java tag handler class to convert Celsius to Fahrenheit
* or Kelvin.
*
* Copyright 2005 by Arnold Doray
*
*   This program is free software; you can redistribute it and/or modify
*   it under the terms of the GNU General Public License as published by
*   the Free Software Foundation; either version 2 of the License, or
*   (at your option) any later version.
*
*   This program is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU General Public License for more details.
*
*   You should have received a copy of the GNU General Public License
*   along with this program; if not, write to the Free Software
*   Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*****************************************************/


import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.BodyContent;


public class Converter extends BodyTagSupport{

    //underscore prefix for private vars
    private String _to = null;

    /* doAfterBody  is inherited from BodyTagSupport and will replace values in a tag that has a body
    It is called after the servlet container reads in
    the tag’s body. This function is where you read the tag’s body, do all necessary processing,
    and display the output. The tag must return an integer flag called EVAL_PAGE, defined for
    you on BodyTagSupport. This flag tells the servlet container to go ahead and process the
    rest of the page. */

    public int doAfterBody(){

        try{

            BodyContent bc = getBodyContent();

            double temperature = Double.parseDouble(bc.getString());

            if(_to == null || _to.length() == 0 || _to.toUpperCase().startsWith("F")){

                bc.getEnclosingWriter().print(toFahrenheit(temperature));

            }else{
        
                bc.getEnclosingWriter().print(toKelvin(temperature));

            }


        }catch(Exception ignore){
            ignore.printStackTrace();
        }
    
        return EVAL_PAGE; //tells servlet container to process rest of JSP page.
    }

    private double toFahrenheit(double c){
        return 32.0 + (c*1.8);
    }

    private double toKelvin(double c){
        return 273.0 + c;
    }

    /** 
        Get and Set methods expected by the servlet container 
    **/

    public String getTo(){ return _to; }
    public void setTo(String t){ _to = t; }

}